package api

import (
	"net/http"

	"servermerge/internal/model"
	"servermerge/internal/service"

	"github.com/gin-gonic/gin"
)

func RegisterRoutes(r *gin.Engine) {
	api := r.Group("/api/merge")
	{
		api.POST("/start", handleMergeStart)
		api.GET("/status/:id", handleGetStatus)
	}
}

// 中台 -> 中控：发起合服
func handleMergeStart(c *gin.Context) {
	var req model.MergeStartRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	resp, err := service.StartMerge(req)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusAccepted, resp)
}

// 查询任务状态
func handleGetStatus(c *gin.Context) {
	id := c.Param("id")
	task := service.GetTaskStatus(id)
	if task == nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "任务不存在"})
		return
	}
	c.JSON(http.StatusOK, task)
}
